export function findStringByHead(array, head) {
  if (!head) return "";
  const re = eval("/^" + head + ".*/i");
  for (const a of array) {
    if (re.test(a)) return a;
  }
  return "";
}

export function formatDate(date, formatString) {
  if (!formatString) {
    formatString = "yyyy-MM-dd hh:mm:ss";
  }
  let o = {
    "M+": date.getMonth() + 1, //月份
    "d+": date.getDate(), //日
    "h+": date.getHours(), //小时
    "m+": date.getMinutes(), //分
    "s+": date.getSeconds(), //秒
    "q+": Math.floor((date.getMonth() + 3) / 3), //季度
    S: date.getMilliseconds(), //毫秒
  };
  if (/(y+)/.test(formatString)) {
    formatString = formatString.replace(
      RegExp.$1,
      (date.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  }
  for (let k in o) {
    if (new RegExp("(" + k + ")").test(formatString)) {
      formatString = formatString.replace(
        RegExp.$1,
        RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
      );
    }
  }
  return formatString;
}

function padding0(s) {
  if (s.length === 1) return "0" + s;
  else return s;
}

export function translateDateString(dateStr) {
  const com = dateStr.split(" ");
  const date = com[0].split("/");
  const time = com[1].split(":");
  date[1] = padding0(date[1]);
  date[2] = padding0(date[2]);
  time[0] = padding0(time[0]);
  time[1] = padding0(time[1]);
  time[2] = padding0(time[2]);
  return date.join("-") + " " + time.join(":");
}

export function deepClone(obj, cache = new WeakMap()) {
  if (!obj || typeof obj !== "object") return obj;
  if (obj instanceof Date) return new Date(obj);
  if (obj instanceof RegExp) return new RegExp(obj);

  if (cache.has(obj)) return cache.get(obj);

  let newObj = Array.isArray(obj) ? [] : {};
  cache.set(obj, newObj);

  for (let key in obj) {
    if (Object.hasOwnProperty.call(obj, key)) {
      newObj[key] = deepClone(obj[key], cache);
    }
  }

  return newObj;
}